﻿using System;
using System.Collections.Generic;
using System.Text;
using DCRF.Common.Core;
using DCRF.Common.Attributes;
using DCRF.Common.Primitive;
using System.Windows.Forms;
using DCRF.Common.Interface;
using DCRF.Common.Connection.Wrappers;

namespace DCRF.BaseBlocks.Log
{
    [BlockId("Logger")]
    public class Logger: BlockBase
    {
        private bool enableLog = true;
        private BlockProperty<Control> containerControl = null;
        private ctlLog myCtl = new ctlLog();

        public Logger(Guid id, IContainerBlockWeb parent)
            : base(id, parent)
        {
        }

        public override void InitBlock()
        {
            base.InitBlock();

            containerControl = new BlockProperty<Control>(this, "ContainerControl");
            containerControl.Connector.EndPointAttached += new Common.Connection.EndPointDelegate(Connector_EndPointAttached);
        }

        void Connector_EndPointAttached(string endpointKey, string connectorKey)
        {
            Control container = containerControl.GetValue();

            container.Invoke(new MethodInvoker(delegate()
                {
                    if (container.Width < myCtl.Width) container.Width = myCtl.Width;
                    if (container.Height < myCtl.Height) container.Height = myCtl.Height;

                    container.Controls.Add(myCtl);
                    myCtl.Dock = DockStyle.Fill;
                }));
        }

        [BlockService]
        public void Log(LogType type, string text)
        {
            if (!enableLog) return;

            //first argument should be type, second should be log
            string log = string.Format("{0} - {1}: {2}", DateTime.Now.ToString("HH:mm:ss"),
                type.ToString(),
                text);

            if (containerControl.Connector.EndPointsCount == 1)
            {
                if (myCtl.ParentForm != null)
                {
                    myCtl.Invoke(new MethodInvoker(delegate()
                    {
                        myCtl.Log(type, log);
                    }));
                }
            }
        }
    }
}
